<template>
  <div class="app-container">
    <div v-if="isEmpty">
      <h2 style="text-align: center;">无已开启教室</h2>
    </div>
    
    <div v-else>
      <div class="tags-view-container">
        <el-tabs v-model="activeName"  type="border-card" @tab-click="tabClick">
          <el-tab-pane v-for="item in Tabs" :key="item.rid" :label="item.name" :name="item.rid.toString()">
            <!-- 参照userlist优化 -->
          </el-tab-pane>
        </el-tabs>
      </div>
      
      <div class="content-container">
        <div class="filter-container">
          <el-row :gutter="12">
            <el-col :span="6">
              <el-input v-model="query.sid" 
                        clearable 
                        placeholder="学号" 
                        @clear="getPage"
                        @keyup.enter.native="handleFilter" />
            </el-col>
            <el-col :span="2">
              <el-button type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
            </el-col>
            <el-col :span="2" :offset="12">
              <el-popover
                placement="bottom"
                width="160"
                v-model="closePopVisible">
                <p>移除此教室不可恢复！</p>
                <div style="text-align: right; margin: 0">
                  <el-button size="mini" type="text" @click="closePopVisible = false">取消</el-button>
                  <el-button type="danger" size="mini" @click="removeThis">确定</el-button>
                </div>
                <el-button slot="reference" 
                           style="margin-left: 10px;" 
                           type="danger" 
                           icon="el-icon-delete" 
                           round>移除</el-button>
              </el-popover>
            </el-col>
            <el-col :span="2" >
              <el-button type="warning" icon="el-icon-close" @click="closeThis">关闭</el-button>
            </el-col>
          </el-row>
        </div>
      <!-- <hr /> -->
      
        <el-table
          :data="pageList"
          stripe
          fit
          highlight-current-row
          style="width: 100%;">
          
          <el-table-column 
            label="序号" 
            type="index"
            align="center" 
            min-width="5%"
            >
          </el-table-column>
          
          <el-table-column 
            label="学号" 
            prop="sid" 
            sortable
            min-width="9%"
            align="center">
          </el-table-column>
          <el-table-column
            label="姓名" 
            prop="student" 
            min-width="6%"
            align="center">
          </el-table-column>
          
          <el-table-column 
            label="机器ID" 
            prop="mid" 
            min-width="20%">
          </el-table-column>
          
          <el-table-column 
            label="IP地址" 
            prop="ip"
            min-width="20%"
            align="center">
          </el-table-column>
          
          <el-table-column 
            label="状态" 
            prop="status"
            align="center"
            min-width="10%">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status | statusFilter">
                {{scope.row.status}}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column 
            label="操作" 
            align="center" 
            min-width="30%" 
            >
            <template slot-scope="scope">
              <el-button 
                type="info" 
                size="mini" 
                plain
                @click="showDetail(scope.row)">详情</el-button>
                
                <!-- <el-popover
                  placement="top"
                  v-model="scope.switchPopVisible">
                  <div>
                    <el-button type="success" size="mini" @click="scope.switchPopVisible = false">开机</el-button>
                    <el-button type="danger" size="mini" @click="scope.switchPopVisible = false">关机</el-button>
                  </div>
                  <el-button slot="reference" 
                             type="warning"
                             size="mini"
                             icon="el-icon-arrow-up" 
                             circle
                             @click="scope.switchPopVisible = true"></el-button>
                </el-popover> -->
                
              <el-button 
                v-if="scope.row.status!='运行中'" 
                size="mini" 
                type="success" 
                @click="handleModifyStatus(scope.row,'运行中')">开机</el-button>
              <el-button 
                v-if="scope.row.status=='运行中'" 
                size="mini" 
                type="danger"
                @click="handleModifyStatus(scope.row,'已关机')">关机</el-button>
              <el-button 
                size="mini" 
                type="primary" 
                @click="connect(scope.row)">远程连接</el-button>
            </template>
          </el-table-column>
        </el-table>
          
        <pagination 
          class="pagination"
          hide-on-single-page 
          :total="total" 
          :page.sync="query.page" 
          :limit.sync="query.limit" 
          @pagination="getPage" />

        <el-dialog
          title="详细信息"
          :visible.sync="dialogVisible"
          width="30%">
          
          <div class="dialog-container">
            <p>{{detail}}</p>
          </div>
          
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
          </span>
        </el-dialog>

      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { fetchRooms, updateRoom, removeRoom } from '@/api/room'
import { updateMachine,fetchMachines } from '@/api/machine'
import Pagination from '@/components/Pagination'

export default {
  name: 'ClassList',
  components: { Pagination },
  data() {
    return {
      activeName: '',
      List:[],
      Tabs:[],
      pageList:[],
      total: 0,
      dialogVisible: false,
      closePopVisible:false,
      switchPopVisible:true,
      query:{
        rid: null,
        tid: null, 
        aid: null,
        sid: null,
        mid: null,
        status:null,
        page: 1,
        limit: 10,
      },
      detail:'',
    }
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        '运行中': 'success',
        '已关机': 'info',
        '挂起': 'warning', 
        'ERROR': 'danger',
        'BUILD': 'primary'
      }
      return statusMap[status]
    },
  },
  computed: {
    ...mapGetters([
      'uid',
      'role',
      'activeRoom',
    ]),
    isAdmin(){
      return this.role == 'Admin'
    },
    isEmpty(){
      return this.Tabs.length == 0
    },
  },
  created() {
    this.getOpenedRooms()
  },
  methods: {
    initName(){
      if(!this.isEmpty) {
        this.activeName = this.Tabs[0].rid
        if(this.activeRoom != 0) this.activeName = this.activeRoom
        this.tabClick()
      }
    },
    getOpenedRooms(){
      this.query.tid = this.uid
      this.query.status = '已开启'//正在运行
      fetchRooms(this.query).then(response => {
        this.Tabs = response.load.roomList
        this.initName()
      }).catch(()=>{
        console.log("获取教室列表失败")
      })
    },
    getList() {
      this.resetQuery()
      fetchMachines(this.query).then(response => {
        this.List = response.load.machineList
        this.total = response.load.total
        this.getPage()
      }).catch(()=>{
        console.log("获取机器列表失败")
      })
    },
    getPage(){
      this.pageList = this.List.filter((item, index) => 
        index < this.query.limit * this.query.page 
        && index >= this.query.limit * (this.query.page - 1))
    },
    resetQuery(){
      this.query.rid = this.activeName
      this.query.page = 1
    },
    tabClick(tab){
      this.$store.dispatch('room/activeRoom', this.activeName).then(()=>{
        this.getList()
      })
    },
    removeThis(){
      this.closePopVisible = false
      this.resetQuery()
      removeRoom(this.query).then(response=>{
        this.removeFromTabs(this.query.rid)
        this.$store.dispatch('room/activeRoom', 0)
        this.initName()
      }).catch(()=>{
        console.log("移除教室失败")
      })
    },
    closeThis(){
      this.resetQuery()
      this.query.status = '锁定'
      updateRoom(this.query).then(response=>{
        this.removeFromTabs(this.query.rid)
        this.$store.dispatch('room/activeRoom', 0)
        this.initName()
      }).catch(()=>{
        console.log("关闭教室失败")
      })
    },
    removeFromTabs(rid){
      for (const [i, v] of this.Tabs.entries()) {
        if (v.rid === rid) {
          this.Tabs.splice(i, 1)
          break
        }
      }
    },
    handleFilter() {
      if(this.query.sid){
        this.pageList = this.List.filter(v=>v.sid == this.query.sid)
      }else{
        this.getPage()
      }
    },
    connect(row) {
      if(row.status != '运行中'){
        this.$message({
          message: '该机器处于非运行状态',
          type: 'error'
        })
        return false//提前终止
      }
      this.$store.dispatch('room/activeVM', row.mid).then(()=>{
        this.$router.replace(`/VNC/index`)
      })
      
    },
    showDetail(row) {
      this.detail = row.profile
      this.dialogVisible = true
    },    

    handleModifyStatus(row, status) {
      this.query.mid = row.mid
      this.query.status = status
      
      updateMachine(this.query).then(response=>{
        row.status = status
        this.$message({
          message: '操作成功 ',
          type: 'success'
        })
      }).catch(()=>{
        console.log("teacher,开启机器失败")
      })
    },
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 0px;
}

.tags-view-container {
  height: 40px;
  width: 100%;
  background: #fff;
  overflow: hidden;
  // box-shadow: 0 1px 4px rgba(0,24,41,.2);
}
.content-container{
  padding: 10px;
  
  .filter-container {
    margin-bottom: 20px;
  }
  .pagination{
    // float: right;
  }
  .dialog-container{
  }
}

</style>
